/*
 * File     : AbstractStructureFactory.java
 * Created  : 24 Apr 2011
 *
 * Copyright © 2011 Matthew Wilson (mj. {my-surname} .uk {at} gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dni.internal.structure;

import com.googlecode.dni.internal.DniInternal;
import com.googlecode.dni.type.NativeObjectList;
import com.googlecode.dni.type.Pointer;
import com.googlecode.dni.type.structure.Structure;
import com.googlecode.dni.type.structure.StructureFactory;

/**
 * <p>
 *  Provides the base functionality for {@link StructureFactory} types.
 * </p>
 *
 * @param <T>
 *            the type of structure
 *
 * @author Matthew Wilson
 */
public abstract class AbstractStructureFactory< T extends Structure >
    implements StructureFactory< T >
{

    /** The structure interface type. */
    private final Class< T > structureType;

    /** The structure implementation type.  Used to stop class GC. */
    @SuppressWarnings( "unused" )
    private Class< ? > structureImplType;

    private StructureRecord record;


    /**
     * @param structureType
     *            the structure interface type
     */
    protected AbstractStructureFactory( final Class< T > structureType )
    {
        this.structureType = structureType;
    }


    //-- StructureFactory methods ----------------------------------------------

    /** {@inheritDoc} */
    @Override
    public final T allocate()
    {
        @SuppressWarnings( "unchecked" )
        T structure = (T) allocateUntyped();
        return structure;
    }

    /** {@inheritDoc} */
    @Override
    public final T fromPointer( final Pointer pointer )
    {
        if ( pointer == null )
        {
            return null;
        }
        return fromPointer( pointer.address() );
    }

    /** {@inheritDoc} */
    @Override
    public final NativeObjectList< T > allocateList( final int size )
    {
        int structureSize = listPreamble( size );
        return new StructureByValueList< T >( this.structureType,
                                              this,
                                              structureSize,
                                              size );
    }

    /** {@inheritDoc} */
    @Override
    public final NativeObjectList< T > listFromPointer( final Pointer pointer, final int size )
    {
        int structureSize = listPreamble( size );
        return new StructureByValueList< T >( pointer,
                                              this.structureType,
                                              this,
                                              structureSize,
                                              size );
    }

    /** {@inheritDoc} */
    @Override
    public NativeObjectList< T > allocatePointerList( final int size )
    {
        if ( size < 0 )
        {
            throw new IllegalArgumentException( "Size: " + size );
        }
        return new StructureByReferenceList< T >( this, size );
    }

    /** {@inheritDoc} */
    @Override
    public NativeObjectList< T > pointerListFromPointer( final Pointer pointer, final int size )
    {
        if ( size < 0 )
        {
            throw new IllegalArgumentException( "Size: " + size );
        }
        return new StructureByReferenceList< T >( this, pointer, size );
    }


    //-- internal methods ------------------------------------------------------

    /**
     * Creates from a pointer.  Used by generated byte-code to avoid excessive
     * byte-code repetition.
     *
     * @param pointer
     *            the pointer
     *
     * @return the structure
     */
    public final T fromPointer( final long pointer )
    {
        if ( pointer == 0L )
        {
            return null;
        }

        @SuppressWarnings( "unchecked" )
        T structure = (T) fromPointerUntyped( pointer );
        return structure;
    }

    /**
     * Creates from a pointer.  Used by generated byte-code to avoid excessive
     * byte-code repetition.
     *
     * @param pointer
     *            the pointer
     *
     * @return the structure
     */
    public final T fromPointer( final int pointer )
    {
        if ( pointer == 0 )
        {
            return null;
        }

        @SuppressWarnings( "unchecked" )
        T structure = (T) fromPointerUntyped( pointer & 0xffffffffL );
        return structure;
    }

    /**
     * @param structureImplType
     *            the structure implementation type
     * @param record
     *            the structure record
     */
    @SuppressWarnings( "hiding" )
    final void init( final Class< ? > structureImplType,
                     final StructureRecord record )
    {
        this.structureImplType = structureImplType;
        this.record = record;
    }


    //-- protected methods -----------------------------------------------------

    /**
     * Creates a new instance using allocated memory.
     *
     * @return a new instance
     */
    protected abstract AbstractStructure allocateUntyped();

    /**
     * Creates a new instance from a pointer.
     *
     * @param pointer
     *            the existing pointer
     *
     * @return a new instance
     */
    protected abstract AbstractStructure fromPointerUntyped( long pointer );

    /**
     * @return the structure impl type
     */
    final Class< T > getStructureType()
    {
        return this.structureType;
    }


    //-- private methods -------------------------------------------------------

    /**
     * Pre-amble for the list factory methods.
     *
     * @param size
     *            the number of elements (for checking)
     * @return the structure size
     */
    private int listPreamble( final int size )
    {
        if ( size < 0 )
        {
            throw new IllegalArgumentException( "Size: " + size );
        }

        // TODO v1.1 at some point, if size is "big", use a sparse impl

        int structureSize = getStructureRecord().getInfo().getSize();
        if ( structureSize < 0 )
        {
            throw new UnsupportedOperationException( "Opaque structure: " + this.structureType.getName() );
        }
        return structureSize;
    }

    private StructureRecord getStructureRecord()
    {
        StructureRecord local = this.record;
        if ( local != null )
        {
            return local;
        }

        DniInternal.LOGGER.warning( "Dodgy threaded code; someone's exposed a StructureFactory without memory barriers" );

        return DniInternal.getStructureRecord( this.structureType );
    }

}
